package io.renren.modules.table.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;

import io.renren.common.utils.R;
import io.renren.modules.com.dao.ComCrChargingitemDao;
import io.renren.modules.com.entity.ComColModel;
import io.renren.modules.com.entity.ComCrChargingitemEntity;
import io.renren.modules.table.entity.AllocationSummaryEntity;
import io.renren.modules.table.service.CollectService;

@Service("collectService")
public class CollectServiceImpl implements CollectService {

	@Autowired
	private ComCrChargingitemDao comCrChargingitemDao;

	public R initialization() {
		return initializationPrivate();
	}

	private R initializationPrivate() {
		Map<String, Object> map = new HashMap<String, Object>();
		SimpleDateFormat sdfwyj = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdfpfp = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdfqyd = new SimpleDateFormat("yyyy年MM月");
		Date nowDate = new Date();
		map.put("dateYearS", sdfwyj.format(nowDate));
		map.put("dateYearE", sdfwyj.format(nowDate));
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(nowDate);
		calendar.set(Calendar.MONTH, calendar.getActualMinimum(Calendar.MONTH));
		map.put("dateMonthS", sdfpfp.format(calendar.getTime()));
		Date sd = calendar.getTime();
		calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
		map.put("dateMonthE", sdfpfp.format(calendar.getTime()));
		Date ed = calendar.getTime();
		// 初始化jqgrid标题名
		map.put("caption", "收款汇总报表(" + sdfqyd.format(sd) + "至" + sdfqyd.format(ed) + ")");
		// 初始化jqgrid表头列名
		map.put("colNames", initializationColNames("1", sd, ed));
		// 初始化jqgrid表头列名属性
		map.put("colModel", initializationColModel("1", sd, ed));
		return R.ok(map);
	}

	public R changeJqGrid(AllocationSummaryEntity allocationSummary) {
		return changeJqGridPrivate(allocationSummary);
	}

	private R changeJqGridPrivate(AllocationSummaryEntity allocationSummary) {
		Map<String, Object> map = new HashMap<String, Object>();
		String dateType = allocationSummary.getYearMonth();
		Date sd = null;
		Date ed = null;
		SimpleDateFormat sdfwyj = null;
		SimpleDateFormat sdf = null;
		if (StringUtils.equals("1", dateType)) {
			sdfwyj = new SimpleDateFormat("yyyy-MM");
			sdf = new SimpleDateFormat("yyyy年MM月");
			sd = DateUtil.parse(allocationSummary.getDateMonthS(), sdfwyj);
			ed = DateUtil.parse(allocationSummary.getDateMonthE(), sdfwyj);
		}
		if (StringUtils.equals("2", dateType)) {
			sdfwyj = new SimpleDateFormat("yyyy");
			sdf = new SimpleDateFormat("yyyy年");
			sd = DateUtil.parse(allocationSummary.getDateYearS(), sdfwyj);
			ed = DateUtil.parse(allocationSummary.getDateYearE(), sdfwyj);
		}
		// 初始化jqgrid标题名
		map.put("caption", "收款汇总报表(" + sdf.format(sd) + "至" + sdf.format(ed) + ")");
		// 初始化jqgrid表头列名
		map.put("colNames", initializationColNames(dateType, sd, ed));
		// 初始化jqgrid表头列名属性
		map.put("colModel", initializationColModel(dateType, sd, ed));
		return R.ok(map);
	}

	private List<String> itemList() {
		List<String> itemList = new ArrayList<String>();
		itemList.add("租金");
		itemList.add("物业费");
		itemList.add("管理费");
		itemList.add("公共能耗费");
		itemList.add("居间服务费");
		itemList.add("保证金");
		itemList.add("停车费");
		itemList.add("租场费");
		itemList.add("其他");
		return itemList;
	}

	/**
	 * 初始化jqgrid表头列名
	 * 
	 * @param dateType
	 * @param sd
	 * @param ed
	 * @return
	 */
	private List<String> initializationColNames(String dateType, Date sd, Date ed) {
		List<String> colNames = CollectionUtil.newArrayList("收款项目", "收款合计");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(sd);
		SimpleDateFormat sdf = null;
		if (StringUtils.equals("1", dateType)) {
			sdf = new SimpleDateFormat("yyyy-MM");
			while (calendar.getTime().before(ed)
					|| StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
				colNames.add(sdf.format(calendar.getTime()));
				calendar.add(Calendar.MONTH, 1);
			}
		}
		if (StringUtils.equals("2", dateType)) {
			sdf = new SimpleDateFormat("yyyy");
			while (calendar.getTime().before(ed)
					|| StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
				colNames.add(sdf.format(calendar.getTime()));
				calendar.add(Calendar.YEAR, 1);
			}
		}
		return colNames;
	}

	/**
	 * 初始化jqgrid表头列名属性
	 * 
	 * @param dateType
	 * @param sd
	 * @param ed
	 * @return
	 */
	private List<ComColModel> initializationColModel(String dateType, Date sd, Date ed) {
		List<ComColModel> colModelList = new ArrayList<ComColModel>();
		// 收款项目
		ComColModel comColModel = new ComColModel();
		comColModel.setName("item");
		comColModel.setWidth(80);
		comColModel.setAlign("center");
		comColModel.setFrozen(true);
		colModelList.add(comColModel);
		// 收款合计
		comColModel = new ComColModel();
		comColModel.setName("totalCollection");
		comColModel.setWidth(100);
		comColModel.setAlign("right");
		colModelList.add(comColModel);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(sd);
		SimpleDateFormat sdf = null;
		if (StringUtils.equals("1", dateType)) {
			sdf = new SimpleDateFormat("yyyy-MM");
			while (calendar.getTime().before(ed)
					|| StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
				comColModel = new ComColModel();
				comColModel.setName(sdf.format(calendar.getTime()));
				comColModel.setWidth(100);
				comColModel.setAlign("right");
				colModelList.add(comColModel);
				calendar.add(Calendar.MONTH, 1);
			}
		}
		if (StringUtils.equals("2", dateType)) {
			sdf = new SimpleDateFormat("yyyy");
			while (calendar.getTime().before(ed)
					|| StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
				comColModel = new ComColModel();
				comColModel.setName(sdf.format(calendar.getTime()) + "year");
				comColModel.setWidth(100);
				comColModel.setAlign("right");
				colModelList.add(comColModel);
				calendar.add(Calendar.YEAR, 1);
			}
		}
		return colModelList;
	}

	public List<Map<String, Object>> queryList(Map<String, Object> map) {
		return queryListPrivate(map);
	}

	private List<Map<String, Object>> queryListPrivate(Map<String, Object> map) {
		List<String> itemList = null;
		if (null != map.get("items") && StringUtils.isNotBlank(map.get("items").toString().trim())
				&& !StringUtils.equals("点击选择...", map.get("items").toString().trim())) {
			itemList = new ArrayList<String>(Arrays.asList(map.get("items").toString().replace(" ", "").split(",")));
		} else {
			itemList = itemList();
		}
		map.put("itemList", itemList);
		SimpleDateFormat sdf = null;
		String yearMonth = map.get("yearMonth").toString();
		Date sd = null;
		Date ed = null;
		if (StringUtils.equals("1", yearMonth)) {
			sdf = new SimpleDateFormat("yyyy-MM");
			sd = DateUtil.parse(map.get("dateMonthS").toString(), sdf);
			ed = DateUtil.parse(map.get("dateMonthE").toString(), sdf);
			map.put("sd", map.get("dateMonthS").toString());
			map.put("ed", map.get("dateMonthE").toString());
		}
		if (StringUtils.equals("2", yearMonth)) {
			sdf = new SimpleDateFormat("yyyy");
			sd = DateUtil.parse(map.get("dateYearS").toString(), sdf);
			ed = DateUtil.parse(map.get("dateYearE").toString(), sdf);
			map.put("sd", map.get("dateYearS").toString());
			map.put("ed", map.get("dateYearE").toString());
		}
		List<ComCrChargingitemEntity> comCrChargingitemList = comCrChargingitemDao.turnover(map);
		if (CollectionUtil.isEmpty(comCrChargingitemList)) {
			return null;
		}
		Map<String, Map<String, Object>> alphabetBear = alphabetBear(comCrChargingitemList, yearMonth, sd, ed);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(sd);
		while (calendar.getTime().before(ed) || StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
			map.put("cherry", sdf.format(calendar.getTime()));
			List<ComCrChargingitemEntity> cherry = comCrChargingitemDao.dancingQueen(map);
			if (StringUtils.equals("1", yearMonth)) {
				for (ComCrChargingitemEntity comCrChargingitemEntity : cherry) {
					if (null != comCrChargingitemEntity.getPayAmount()) {
						alphabetBear.get(comCrChargingitemEntity.getChargingItem()).put(sdf.format(calendar.getTime()),
								comCrChargingitemEntity.getPayAmount());
					}
				}
				calendar.add(Calendar.MONTH, 1);
			}
			if (StringUtils.equals("2", yearMonth)) {
				for (ComCrChargingitemEntity comCrChargingitemEntity : cherry) {
					if (null != comCrChargingitemEntity.getPayAmount()) {
						alphabetBear.get(comCrChargingitemEntity.getChargingItem())
								.put(sdf.format(calendar.getTime()) + "year", comCrChargingitemEntity.getPayAmount());
					}
				}
				calendar.add(Calendar.YEAR, 1);
			}
		}
		List<Map<String, Object>> chinaJoy = new ArrayList<Map<String, Object>>();
		for (String item : itemList) {
			if (null != alphabetBear.get(item)) {
				chinaJoy.add(alphabetBear.get(item));
			}
		}
		return chinaJoy;
	}

	private Map<String, Map<String, Object>> alphabetBear(List<ComCrChargingitemEntity> comCrChargingitemList,
			String dateType, Date sd, Date ed) {
		Map<String, Map<String, Object>> alphabetBear = new HashMap<String, Map<String, Object>>();
		String item = null;
		for (ComCrChargingitemEntity comCrChargingitemEntity : comCrChargingitemList) {
			Map<String, Object> map = new HashMap<String, Object>();
			item = comCrChargingitemEntity.getChargingItem();
			map.put("item", item);
			if (null != comCrChargingitemEntity.getPayAmount()) {
				map.put("totalCollection", comCrChargingitemEntity.getPayAmount());
			} else {
				map.put("totalCollection", "");
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sd);
			SimpleDateFormat sdf = null;
			if (StringUtils.equals("1", dateType)) {
				sdf = new SimpleDateFormat("yyyy-MM");
				while (calendar.getTime().before(ed)
						|| StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
					map.put(sdf.format(calendar.getTime()), "");
					calendar.add(Calendar.MONTH, 1);
				}
			}
			if (StringUtils.equals("2", dateType)) {
				sdf = new SimpleDateFormat("yyyy");
				while (calendar.getTime().before(ed)
						|| StringUtils.equals(sdf.format(calendar.getTime()), sdf.format(ed))) {
					map.put(sdf.format(calendar.getTime()) + "year", "");
					calendar.add(Calendar.YEAR, 1);
				}
			}
			alphabetBear.put(item, map);
		}
		return alphabetBear;
	}

	public int queryTotal(Map<String, Object> map) {
		return comCrChargingitemDao.turnoverTotal(map);
	}

	public void export(OutputStream out, Map<String, Object> map) {
		exportPrivate(out, map);
	}

	private void exportPrivate(OutputStream out, Map<String, Object> map) {
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet();
		// 生成数字样式
		HSSFCellStyle numberStyle = workbook.createCellStyle();
		numberStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
		// 生成文字样式
		HSSFCellStyle style = workbook.createCellStyle();
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成excel内容
		String dateType = map.get("yearMonth").toString();
		Date sd = null;
		Date ed = null;
		SimpleDateFormat sdf = null;
		if (StringUtils.equals("1", dateType)) {
			sdf = new SimpleDateFormat("yyyy-MM");
			sd = DateUtil.parse(map.get("dateMonthS").toString(), sdf);
			ed = DateUtil.parse(map.get("dateMonthE").toString(), sdf);
		}
		if (StringUtils.equals("2", dateType)) {
			sdf = new SimpleDateFormat("yyyy");
			sd = DateUtil.parse(map.get("dateYearS").toString(), sdf);
			ed = DateUtil.parse(map.get("dateYearE").toString(), sdf);
		}
		List<String> colNames = initializationColNames(dateType, sd, ed);
		HSSFRow rowOne = sheet.createRow(0);
		HSSFCell cell = null;
		for (int i = 0; i < colNames.size(); i++) {
			cell = rowOne.createCell(i);
			cell.setCellStyle(style);
			cell.setCellValue(colNames.get(i));
		}
		List<ComColModel> colModel = initializationColModel(dateType, sd, ed);
		List<Map<String, Object>> chinaJoy = queryList(map);
		for (int i = 0; i < chinaJoy.size(); i++) {
			Map<String, Object> alphabetBear = chinaJoy.get(i);
			HSSFRow row = sheet.createRow(i + 1);
			for (int j = 0; j < colModel.size(); j++) {
				cell = row.createCell(j);
				if (j < 1) {
					cell.setCellStyle(style);
				} else {
					cell.setCellStyle(numberStyle);
				}
				cell.setCellValue(alphabetBear.get(colModel.get(j).getName()).toString());
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
